<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :destroyOnClose="true"
      :title="title + '商品'"
      :width="modalWidth"
      @ok="handleOk"
      @cancel="handleClose"
      :visible="visible"
      :confirm-loading="confirmLoading"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="handleOk" type="primary">确认</a-button>
        </div>
      </template>
      <a-spin :spinning="confirmLoading">
        <a-form-model ref="ruleForm" :model="model" :rules="rules">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="商品名称"
                prop="goodsName"
                hasFeedback
              >
                <a-input
                  placeholder="请输入商品名称"
                  v-model.trim="model.goodsName"
                />
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="商品类型"
                hasFeedback
                prop="goodsTypeId"
              >
                <a-tree-select
                  v-model.trim="model.goodsTypeId"
                  style="width: 100%"
                  :dropdown-style="{
                    maxHeight: '400px',
                    overflow: 'auto',
                  }"
                  :tree-data="treeData"
                  :replaceFields="replaceFields"
                  placeholder="请选择商品类型"
                  tree-default-expand-all
                  @change="goodTypeChange"
                  v-if="treeData.length > 0"
                ></a-tree-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="计量单位"
                prop="unit"
                hasFeedback
              >
                <a-select
                  v-model.trim="model.unit"
                  placeholder="请选择计量单位"
                >
                  <a-select-option
                    v-for="item in measureOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.dictName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="来源"
                prop="source"
                hasFeedback
              >
                <a-select
                  v-model.trim="model.source"
                  :disabled="title === '编辑'"
                  placeholder="请选择来源"
                >
                  <a-select-option
                    v-for="item in sourceOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.dictName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>

          <!-- line-2 -->
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="商品编号"
                prop="goodsCode"
                hasFeedback
              >
                <div class="flex flex-a-c ">
                  <a-input
                    placeholder="请输入商品编号"
                    v-model.trim="model.goodsCode"
                  />
                </div>
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="图号"
                hasFeedback
                prop="figureNum"
              >
                <a-input
                  placeholder="请输入图号"
                  v-model.trim="model.figureNum"
                />
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="采购单价"
                prop="unitPrice"
                hasFeedback
              >
                <a-input
                  v-model.trim="model.unitPrice"
                  placeholder="请输入采购单价"
                  suffix="元"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="最低库存"
                hasFeedback
                prop="minStock"
              >
                <a-input
                  placeholder="请输入最低库存"
                  v-model.trim="model.minStock"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="品牌"
                hasFeedback
              >
                <a-input
                  disabled
                  placeholder="请输入品牌"
                  v-model.trim="model.brand"
                />
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="重量"
                hasFeedback
              >
                <a-input placeholder="请输入重量" v-model.trim="model.weight" />
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="规格"
                prop="specifications"
                hasFeedback
              >
                <a-input
                  placeholder="请输入规格"
                  v-model.trim="model.specifications"
                />
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="供应商"
                hasFeedback
              >
                <a-select
                  :open="false"
                  :defaultOpen="false"
                  mode="multiple"
                  :allowClear="true"
                  placeholder="请选择供应商"
                  v-model.trim="model.supplierId"
                  @dropdownVisibleChange="
                    (open) =>
                      handleTableSelect(
                        open,
                        'supplierId',
                        'tableModal',
                        '商供应商品'
                      )
                  "
                  @change="
                    (value) => handleChange(value, 'supplierId', supplierModel)
                  "
                >
                  <a-select-option
                    v-for="item in supplierModel.tableOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- line-2 -->
          <a-row :gutter="24">
            <!-- <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="常用库位"
                hasFeedback
              >
                <a-input
                  placeholder="请输入常用库位"
                  v-model.trim="model.commonLocation"
                />
              </a-form-model-item>
            </a-col> -->

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="备注"
                hasFeedback
              >
                <a-input placeholder="请输入备注" v-model.trim="model.remark" />
              </a-form-model-item>
            </a-col>

            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="产品线"
                hasFeedback
              >
                <a-select
                  :open="false"
                  :defaultOpen="false"
                  mode="multiple"
                  :allowClear="true"
                  placeholder="请选择产品线"
                  v-model.trim="model.productLineId"
                  @dropdownVisibleChange="
                    (open) =>
                      handleTableSelect(
                        open,
                        'productLineId',
                        'tableLineModal',
                        '产品线'
                      )
                  "
                  @change="
                    (value) =>
                      handleChange(value, 'productLineId', productLineModel)
                  "
                >
                  <a-select-option
                    v-for="item in productLineModel.tableOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="上传图片"
                hasFeedback
              >
                <ImageUpload v-model.trim="model.picture"></ImageUpload>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-spin>
    </a-modal>
    <!-- 供应商选择 -->
    <TableSelectModal
      :columns="supplierModel.columns"
      :replaceFields="supplierModel.replaceFields"
      :treeKey="supplierModel.treeKey"
      :tableKey="supplierModel.tableKey"
      :searchKey="supplierModel.searchKey"
      :name="supplierModel.name"
      :code="supplierModel.code"
      :filename="supplierModel.filename"
      ref="tableModal"
      @tableSelect="tableSelect"
    ></TableSelectModal>
    <!-- 产品线选择 -->
    <TableSelectModal
      :columns="productLineModel.columns"
      :replaceFields="productLineModel.replaceFields"
      :tableKey="productLineModel.tableKey"
      :name="productLineModel.name"
      :code="productLineModel.code"
      :filename="productLineModel.filename"
      ref="tableLineModal"
      @tableSelect="tableLineSelect"
    ></TableSelectModal>
  </div>
</template>

<script>
import ImageUpload from "@/components/upload/ImageUpload";
import TableSelectModal from "@/components/TableSelectModal";
import api from "@/api/apiServer";
import { getCode } from "@/unit/tool";
import pinyin from "js-pinyin";
import { isNum } from "@/unit/rule";
import {
  supplierModel,
  productLineModel,
} from "@/pages/Commodity/components/tableConfig";
export default {
  props: {
    treeData: {
      type: Array,
    },
  },
  components: { ImageUpload, TableSelectModal },
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      modalWidth: 1677, // 抽屉宽度
      model: {
        goodsName: "",
      },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
      confirmLoading: false,
      sourceOption: [], // 数据来源
      measureOption: [], // 计量单位
      unitOption: [{ id: 1, name: "个" }],
      replaceFields: {
        children: "goodsTypeList",
        title: "goodsTypeName",
        key: "id",
        value: "id",
      },
      // 供应商
      supplierModel,
      // 产品线
      productLineModel,
    };
  },
  computed: {
    rules() {
      return {
        goodsCode: [
          { required: true, message: "请输入商品编号", trigger: "change" },
        ],
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "change" },
        ],
        unit: [
          { required: true, message: "请选择计量单位", trigger: "change" },
        ],
        source: [{ required: true, message: "请选择来源", trigger: "change" }],
        goodsTypeId: [
          { required: true, message: "请选择商品类型", trigger: "change" },
        ],
        figureNum: [
          { required: true, message: "请输入图号", trigger: "change" },
        ],
        minStock: [{ validator: isNum, trigger: "change" }],
        unitPrice: [{ validator: isNum, trigger: "change" }],
      };
    },
  },
  methods: {
    // 供应商选择
    tableSelect(result, tableOption) {
      this.supplierModel.tableOption = tableOption;
      let supplierId = [];
      result.forEach((item) => {
        supplierId.push(item.id);
      });
      this.$set(this.model, "brand", result[0].brand);
      this.$set(this.model, "supplierId", supplierId);
      this.$refs.ruleForm.clearValidate(["supplierId"]);
    },
    tableLineSelect(result, tableOption) {
      this.productLineModel.tableOption = tableOption;
      let productLineId = result[0].id;
      this.$set(this.model, "productLineId", productLineId);
      this.$refs.ruleForm.clearValidate(["productLineId"]);
    },
    // 商品选择
    handleTableSelect(open, key, refName, name) {
      this.$refs[refName].title = name;
      this.$refs[refName].modalAdd();
      if (this.model[key]) {
        let arr = this.model[key].toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs[refName].selectedRowKeys = newArr;
        } else {
          this.$refs[refName].selectedRowKeys = [];
        }
      }
    },
    // 事件选择回调
    handleChange(value, key, model) {
      if (value.length > 0) {
        if (model.mode) {
          this.model[key] = value;
        } else {
          this.model[key] = value.toString();
        }
      } else {
        delete this.model[key];
      }
    },

    // 助记码
    getPinYin(name) {
      var char = "";
      pinyin.setOptions({ checkPolyphone: false, charCase: 0 });
      /**
       * 跟据传入文字调用方法进行转换
       */
      if (name) {
        char = pinyin.getCamelChars(name);
      }
      /**
       * 赋值检索码
       */
      this.$set(this.model, "mnemonicCode", char);
    },

    // 获取供应商列表
    async getSupplier(id) {
      let params = { id, pageNumber: 1, pageSize: 10, deleteFlag: "N" };
      const res = await api.SupplierList(params);
      this.supplierModel.tableOption = res.data.data;
    },
    // 获取产品线列表
    async getProductLine(id) {
      let params = { id, pageNumber: 1, pageSize: 10, deleteFlag: "N" };
      const res = await api.ProductLinePage(params);
      this.productLineModel.tableOption = res.data.data;
    },
    changeRadio(name, value) {
      this.model[name] = value;
    },
    // 商品编号自动检测
    goodTypeChange(value, label, extra) {
      let goodsCode = getCode(
        this.treeData,
        "goodsTypeList",
        value,
        "goodsTypeCode"
      );
      this.$set(this.model, "goodsCode", goodsCode);
    },
    // 获取数据来源
    async getDictFindByCode(parentCode, key) {
      const res = await api.DictFindByCode({ parentCode });
      this[key + "Option"] = res.data;
    },
    // 新增
    modalAdd() {
      this.modalEdit({});
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.visible = true;
      this.getDictFindByCode("dict.source", "source");
      this.getDictFindByCode("dict.measure", "measure");
      if (record.id) {
        this.getSupplier(record.supplierId);
        this.getProductLine(record.productLineId);
      }
      this.model = Object.assign({}, record);
      if (this.model.supplierId === null) {
        delete this.model.supplierId;
      }
      if (this.model.productLineId === null) {
        delete this.model.productLineId;
      }
    },
    async submitVulFun() {
      this.confirmLoading = true;
      if (this.model.supplierId) {
        let newArr = this.model.supplierId;
        this.$set(this.model, "supplierId", Number(newArr.toString()));
      }
      let res;
      if (!this.model.id) {
        res = await api.CommodityAdd(this.model);
      } else {
        res = await api.CommodityEdit(this.model);
      }
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.confirmLoading = false;
      this.$message.success(res.message);
      this.$emit("ok");
      this.visible = false;
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.submitVulFun();
        } else {
          return false;
        }
      });
    },
    // 关闭
    handleClose() {
      this.visible = false;
      this.$refs.ruleForm.resetFields();
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.modalWidth = screenWidth;
      } else {
        this.modalWidth = 1677;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.formBox {
  width: 100%;
  border: 1px solid #e9e9e9;
  padding: 10px 16px;
  margin: 18px 0;
  .requiredNews {
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    color: #1a5eff;
    margin-bottom: 12px;
  }

  .ant-calendar-picker {
    width: 100%;
  }
}
</style>
